package user.controllers;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import user.forms.UserForm;
import user.models.UserModel;

import entities.ApplicationConfig;
import entities.User;

public class ProfileEditServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		
		TreeMap check = new TreeMap();
		User user = null;
		if (request.getUserPrincipal() != null) {
			UserModel userModel = UserModel.getInstance();
			user = userModel.getByUsername(appConfig.getApplicationId(), request.getUserPrincipal().getName());
		}
		
		if (user == null) {
			response.sendRedirect("/msg/require-login");
			return;
		}
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/user/pages/profile_edit.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		
		User user = null;
		if (request.getUserPrincipal() != null) {
			UserModel userModel = UserModel.getInstance();
			user = userModel.getByUsername(appConfig.getApplicationId(), request.getUserPrincipal().getName());
		}
		
		if (user == null) {
			response.sendRedirect("/msg/require-login");
			return;
		}
		
		TreeMap forms = (TreeMap) UserForm.checkValid(request, user);
		user = (User) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if (check.size() == 0) {
			UserModel userModel = UserModel.getInstance();
			userModel.insert(appConfig.getApplicationId(), user);
			request.setAttribute("user_logged_in", user);
			request.setAttribute("success", "Change your profile success!");
		}
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/user/pages/profile_edit.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
